package com.tybbank.Activity;

import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tybbank.Adapter.UpdateContentAdapter;
import com.tybbank.Base.BaseActivity;
import com.tybbank.Bean.GetVersionBean;
import com.tybbank.Fragment.GoodsFragment;
import com.tybbank.Fragment.HomeFragment;
import com.tybbank.Fragment.MeFragment;
import com.tybbank.MyApplication;
import com.tybbank.R;
import com.tybbank.Utils.Constant;
import com.tybbank.Utils.FileProvider7;
import com.tybbank.Utils.logUtilssss;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends BaseActivity {


    public static final long TWO_SECOND = 2 * 1000;
    //选择和强制更新相关
    private static final int REQUESTPERMISSION = 201;
    @BindView(R.id.rb_home)
    RadioButton rbHome;
    @BindView(R.id.rb_goods)
    RadioButton rbGoods;
    @BindView(R.id.rb_me)
    RadioButton rbMe;
    @BindView(R.id.rg_tab)
    RadioGroup rgTab;
    @BindView(R.id.vp)
    FrameLayout vp;
    long preTime;
    private HomeFragment fragment1;
    private GoodsFragment fragment2;
    private MeFragment fragment3;
    private String login;
    private String token;
    private FragmentManager fm;
    private boolean needSwitch = true;//设置切换了RadioGroup之后，Fragment是否切换显示，false不显示，true显示
    private String version;
    private String versionName;
    private String downloadUrl;
    private ProgressDialog downloadDialog;
    private File file;
    private List<String> updateContent = new ArrayList<>();
    private RelativeLayout rl_prograssbar;
    private ProgressBar progressBar;
    private TextView tv_prograss;
    private GetVersionBean<GetVersionBean.AndroidBean> versionData;
    private int item;
    private String uuid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        LoadData();
        MyApplication.token = token;
        MyApplication.uuid = uuid;
        fm = getSupportFragmentManager();
        initFragment();
    check();//检查权限 升级

    }




    private void initFragment() {
        rgTab.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                needSwitch = true;
                int index = 0;
                switch (i) {
                    case R.id.rb_home: //首页
                        if (Build.VERSION.SDK_INT >= 21) {
                            View decorView = getWindow().getDecorView();
                            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                            decorView.setSystemUiVisibility(option);
                            getWindow().setStatusBarColor(Color.TRANSPARENT);
                        }
                        index = 0;
                        break;
                    case R.id.rb_goods://商城
                        if (Build.VERSION.SDK_INT >= 21) {
                            View decorView = getWindow().getDecorView();
                            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                            decorView.setSystemUiVisibility(option);
                            getWindow().setStatusBarColor(Color.TRANSPARENT);
                        }
                        index = 1;
                        break;

                    case R.id.rb_me://我的
                        if (Build.VERSION.SDK_INT >= 21) {
                            View decorView = getWindow().getDecorView();
                            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                            decorView.setSystemUiVisibility(option);
                            getWindow().setStatusBarColor(Color.TRANSPARENT);
                        }
                        index = 2;
                        break;
                    default:
                        break;
                }

                switchFragment(index);
            }
        });

//改为登录不登录都进入我的
        ((RadioButton) rgTab.getChildAt(0)).setChecked(true);

    }

    //切换Fragment
    public void switchFragment(int index) {
        FragmentTransaction ft = fm.beginTransaction();
        if (needSwitch) {
            hideFragment(ft);
        }
        switch (index) {
            case 0://首页
                if (fragment1 != null) {
                    ft.show(fragment1);
                } else {
                    fragment1 = new HomeFragment();
                    ft.add(R.id.vp, fragment1);
                }
                break;
            case 1://商城
                if (fragment2 != null) {
                    ft.show(fragment2);
                } else {
                    fragment2 = new GoodsFragment();
                    ft.add(R.id.vp, fragment2);
                }
                break;
            case 2://wo d
                if (fragment3 != null) {
                    ft.show(fragment3);
                } else {
                    fragment3 = new MeFragment();
                    ft.add(R.id.vp, fragment3);
                }
                break;
            default:
                break;
        }
        ft.commit();
    }

    //隐藏所有的fragment
    private void hideFragment(FragmentTransaction ft) {
        if (fragment1 != null) {
            ft.hide(fragment1);
        }
        if (fragment2 != null) {
            ft.hide(fragment2);
        }
        if (fragment3 != null) {
            ft.hide(fragment3);
        }

    }



    //获取保存的账号
    public void LoadData() {
        //指定操作的文件名称
        SharedPreferences share = getSharedPreferences("user", 0);
        token = share.getString("token", "");
        uuid = share.getString("uuid", "");

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 截获后退键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long currentTime = new Date().getTime();

            // 如果时间间隔大于2秒, 不处理
            if ((currentTime - preTime) > TWO_SECOND) {
                // 显示消息
                Toast.makeText(this, getString(R.string.outapp),
                        Toast.LENGTH_SHORT).show();

                // 更新时间
                preTime = currentTime;

                // 截获事件,不再处理
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 22:
                installApk();
                break;

            default:
                break;
        }
    }

    //检查权限
    private void check() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUESTPERMISSION);
            Toast.makeText(this, "请允许权限进行下载安装", Toast.LENGTH_SHORT);
        } else {
            initUpdataApp();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUESTPERMISSION) {
            if (permissions[0].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    initUpdataApp();
                }
            }
        }
    }
    //版本号
    public static int getVersionCode(Context context) {
        return getPackageInfo(context).versionCode;
    }
    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }
    /**
     * 初始化 应用信息 判断是否更新应用
     */
    private void initUpdataApp() {
        OkHttpUtils
                .post()
                .url(Constant.edition)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        Toast.makeText(getBaseContext(), getString(R.string.error), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        logUtilssss.e("TAG版本升级" + response.toString());
                        reponse(response);
                    }

                    private void reponse(String json) {
                        try{
                            GetVersionBean enterBean = new Gson().fromJson(json, new TypeToken<GetVersionBean>() {
                            }.getType());
                            int a = (enterBean.getCode());
                            //SaveData
                            if (a == 1011) {
                                versionData = new Gson().fromJson(json, new TypeToken<GetVersionBean<GetVersionBean.AndroidBean>>() {
                                }.getType());
                                versionName = versionData.getAndroid().getEdition();
                                updateContent = versionData.getAndroid().getInfo();
                                //更新app,如果服务器版本号大于本地版本号
                                    logUtilssss.e("TAG系统版本号" + versionData.getAndroid().getNumber() + "");
                                    logUtilssss.e("TAG本地版本号" + getPackageInfo().versionCode + "");
                                    if (Integer.parseInt(versionData.getAndroid().getNumber()) > getPackageInfo().versionCode) {
                                        showUpdateAppInfoDialog();
                                    } else {
                                        return;
                                    }

                            }
                        }catch (Exception e){

                        }

                    }
                });
    }

    //新的提示更新窗
    private void showUpdateAppInfoDialog() {
        if (versionData != null) {
//            version = versionData.getData().getVersion();
            downloadUrl = versionData.getAndroid().getUrl();
            //    Log.e("下载地址", downloadUrl);
        }
        final Dialog dialog = new Dialog(this, R.style.My_dialog);
        View v = LayoutInflater.from(this).inflate(R.layout.dialog_update_app, null);

        TextView tv_update_title = (TextView) v.findViewById(R.id.tv_update_title);
        ListView lv_update_content = (ListView) v.findViewById(R.id.lv_update_content);
        final Button bt_update = (Button) v.findViewById(R.id.bt_update);
        rl_prograssbar = (RelativeLayout) v.findViewById(R.id.rl_prograssbar);
        tv_prograss = (TextView) v.findViewById(R.id.tv_prograss);
        progressBar = (ProgressBar) v.findViewById(R.id.progressBar);

        tv_update_title.setText(getString(R.string.version)+"(" + versionName + ")");//更新的标题
        //设置更新内容
        UpdateContentAdapter updateContentAdapter = new UpdateContentAdapter(this, updateContent);
        lv_update_content.setAdapter(updateContentAdapter);
        bt_update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rl_prograssbar.setVisibility(View.VISIBLE);
                bt_update.setVisibility(View.GONE);
                loadApk(downloadUrl,dialog);
            }
        });

        dialog.setContentView(v);//自定义布局应该在这里添加，要在dialog.show()的后面
        Window diaWindow = dialog.getWindow();
        diaWindow.setGravity(Gravity.CENTER);//可以设置显示的位置
        diaWindow.setWindowAnimations(R.style.dialog_anim);  //添加动画
        //   将对话框的大小按屏幕大小的百分比设置
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay();  // 获取屏幕宽、高用
        WindowManager.LayoutParams lp = diaWindow.getAttributes();
        lp.height = (int) (d.getHeight() * 0.45);   // 高度设置为屏幕的0.5
        lp.width = (int) (d.getWidth() * 0.7);    // 宽度设置为屏幕的0.7
        diaWindow.setAttributes(lp);
        dialog.setCancelable(false);
        dialog.show();
    }

    //下载app
    public void loadApk(String url, final Dialog dialog) {
        Request request = new Request.Builder().url(url).tag(this).build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        Toast.makeText(MainActivity.this,getString(R.string.shibai), Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) {
                if (response.code() == 200) {
                    file = saveFile(response);
                    if (file != null) {
                        checkIsAndroidO();
                    }
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dismiss();
                            Toast.makeText(MainActivity.this, getString(R.string.shibai), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        });
    }

    /**
     * 判断是否是8.0,8.0需要处理未知应用来源权限问题,否则直接安装
     */
    private void checkIsAndroidO() {
        if (Build.VERSION.SDK_INT >= 26) {
            boolean b = getPackageManager().canRequestPackageInstalls();
            if (b) {
                installApk();//安装应用的逻辑(写自己的就可以)
            } else {
                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, 22);
            }
        } else {
            installApk();
        }
    }

    private void installApk() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        FileProvider7.setIntentDataAndType(MainActivity.this,
                intent, "application/vnd.android.package-archive", file, true);

        startActivity(intent);
    }

    /**
     * 保存文件
     *
     * @param response
     * @return
     */
    public File saveFile(Response response) {
        InputStream is = null;
        byte[] buf = new byte[2048];
        int len;
        FileOutputStream fos = null;
        File file = null;
        try {
            is = response.body().byteStream();
            final float total = response.body().contentLength();
            progressBar.setMax((int) ((total / 1024) / 1024));
            long sum = 0;
            //文件存放地址
            File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/download");
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //下载完之后apk的名字
            file = new File(dir, "bibank.apk");
            fos = new FileOutputStream(file);
            while ((len = is.read(buf)) != -1) {
                sum += len;
                fos.write(buf, 0, len);
                final Long finalSum = sum;
                progressBar.setProgress((int) ((finalSum / 1024) / 1024));
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // TODO total总长度，finalSum下载长度
                        double i = finalSum / (double) total * 100;
                        int progress = (int) Math.ceil(i);
                        tv_prograss.setText(progress + "%");//设置进度百分比
                    }
                });

            }

            fos.flush();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (fos != null)
                    fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }
}
